package com.example.imitation_webchat_demo.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.imitation_webchat_demo.R;
import com.example.imitation_webchat_demo.event.FriendshipEvent;
import com.example.imitation_webchat_demo.event.LoginEvent;
import com.example.imitation_webchat_demo.model.Resource;
import com.example.imitation_webchat_demo.thread.FetchFriendshipRunnable;
import com.example.imitation_webchat_demo.thread.LoginRunnable;
import com.example.imitation_webchat_demo.util.AppUtils;
import com.example.imitation_webchat_demo.util.ApplicationUtils;
import com.example.imitation_webchat_demo.util.BPUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import de.greenrobot.event.EventBus;

// 登录页面
public class LoginActivity extends Activity {
	@ViewInject(R.id.login_username)
	private EditText usernameText;

	@ViewInject(R.id.login_password)
	private EditText passwordText;

	@ViewInject(R.id.login_vertification)
	private EditText vertificationText;

	@ViewInject(R.id.login_vertification_image)
	private ImageView vertificationView;

	private String username;
	private String password;
	private String vertification;
	private String userId;

	private ProgressDialog dialog;
	private String friendshipInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置无标题模式
		setContentView(R.layout.activity_login);

		ViewUtils.inject(this);
		EventBus.getDefault().register(this);
		initComponent(); // 初始化控件
		
		ApplicationUtils.getInstance().addActivity(this);
	}

	// 得到控件里的值
	private void getComponentValues() {
		username = usernameText.getText().toString().trim();
		password = passwordText.getText().toString().trim();
		vertification = vertificationText.getText().toString().trim();
	}

	// 初始化控件
	private void initComponent() {
		dialog = new ProgressDialog(this);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setMessage("正在登陆，请稍候...");
		AppUtils.setImageResource(vertificationView); // 初始化验证码，在imageview中显示验证码
	}

	// 点击返回箭头
	@OnClick(R.id.login_head_back)
	private void back(View view) {
		AppUtils.hideSoftInputWindow(this, usernameText);
		finish();
	}

	// 点击验证码图片
	@OnClick(R.id.login_vertification_image)
	private void switchImage(View view) {
		AppUtils.setImageResource(vertificationView); // imageview切换验证码
	}

	// 点击登录按钮
	@OnClick(R.id.login_login_btn)
	private void login(View view) {
		getComponentValues();

		AppUtils.hideSoftInputWindow(this, usernameText);
		if (username == null || username.equals("")) {
			AppUtils.showToast(this, "用户名不能为空，请重新输入");
			AppUtils.setFocus(usernameText);
			return;
		}
		if (password == null || password.equals("")) {
			AppUtils.showToast(this, "密码不能为空，请重新输入");
			AppUtils.setFocus(passwordText);
			return;
		}
		if (!AppUtils.isCharacterOrDigital(username)) {
			AppUtils.showToast(this, "用户名只能是数字和字母的组成，请重新输入");
			AppUtils.setFocus(usernameText);
			return;
		}
		if (AppUtils.containChineseChar(password)) {
			AppUtils.showToast(this, "密码不能包含中文，请重新输入");
			AppUtils.setFocus(passwordText);
			return;
		}
		if (!vertification.equalsIgnoreCase(BPUtils.getInstance().getCode())) {
			AppUtils.showToast(this, "验证码错误，请重新输入");
			AppUtils.setFocus(vertificationText);
			return;
		}
		
		AppUtils.setImageResource(vertificationView); // imageview切换验证码
		sendMsgToServer();
	}

	// 发送消息到服务器
	private void sendMsgToServer() {
		dialog.show();
		List<String> list = new ArrayList<String>();
		list.add(username);
		list.add(password);
		new Thread(new LoginRunnable(this, list)).start();
	}

	// 处理登录事件后的返回响应
	public void onEventMainThread(LoginEvent event) {
		if (event != null) {
			String result = event.getResult();
			
			if (result != null) {
				if (result.contains("username not exist")) {
					AppUtils.showToast(this, "用户名错误");
					dialog.dismiss();
				} else if (result.contains("password error")) {
					AppUtils.showToast(this, "密码错误");
					dialog.dismiss();
				} else {
					userId = result.split(";")[1];
					getUserFriendshipInfo();    // 获取用户的好友信息
					putUsernameIntoShare();   //将用户名存入sharepreference中
				}
			} else {
				AppUtils.showToast(this, Resource.disconnectionTip);
				dialog.dismiss();
			}
		}
	}
	
	//获取用户的好友信息
	private void getUserFriendshipInfo(){
		dialog.setMessage("登陆成功，正在获取用户信息...");
		dialog.show();
		List<String> list = new ArrayList<String>();
		list.add(userId);
		new Thread(new FetchFriendshipRunnable(this, list)).start();
	}
	
	//获取用户好友信息的回调响应方法
	public void onEventMainThread(FriendshipEvent event){
		dialog.dismiss();
		if(event != null){
			String result = event.getResult();
			
			if(result != null){
				friendshipInfo = result;
				jumpToMainActivity();       // 跳到主页面
			}else{
				AppUtils.showToast(this, Resource.disconnectionTip);
			}
		}
	}
	
	//将用户id存入sharepreference中
	private void putUsernameIntoShare(){
		Editor editor = getSharedPreferences(Resource.appName, Context.MODE_PRIVATE).edit();
		editor.putString("username", username);
		editor.putString("userId", userId);
		editor.commit();
	}
	
	// 跳到主页面
	private void jumpToMainActivity(){
		Intent intent = new Intent(this, MainActivity.class);
		intent.putExtra("username", username);
		intent.putExtra("friendshipInfo", friendshipInfo);
		startActivity(intent);
		finish();
	}

	// 点击注册按钮
	@OnClick(R.id.login_register_btn)
	private void register(View view) {
		AppUtils.hideSoftInputWindow(this, usernameText);
		
		Intent intent = new Intent(this, RegisterActivity.class);
		startActivity(intent);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		AppUtils.setImageResource(vertificationView); // imageview切换验证码
		username = intent.getStringExtra("username");
		usernameText.setText(username);
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		ApplicationUtils.getInstance().removeActivity(this);
		super.onDestroy();
	}
}